import React, { useEffect, useState } from 'react';

import { ProColumns, ProTable } from '@/components/Pro';
import {
  realTimeMonitoringControllerDeviceTypes,
  realTimeMonitoringControllerOfflineOverview as offList,
} from '@/services/ess/realTimeMonitoring';
import { stationAreaControllerImplListStationArea as areaList } from '@/services/ess/stationArea';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useIntl } from 'umi';
import {
  useParams,
  useSelectedDeviceNode,
  useSetSelectedDevice,
} from '../../SelectedDeviceNodeContext';
import Styles from './index.less';

interface Props {
  showArea?: boolean;
}

export const OfflineOverview: React.FC<Props> = ({ showArea = false }) => {
  const deviceNode = useSelectedDeviceNode();
  const setSelectedDevice1 = useSetSelectedDevice();
  const [partitions, setPartitions] = useState([]);
  // const [deviceList, setDeviceList] = useState([]);
  // console.log(deviceList);
  const intl = useIntl();
  const params = useParams();
  useEffect(() => {
    (async () => {
      try {
        let reslut = await areaList();
        if (reslut.success) {
          let arr = reslut.data?.map((item) => {
            return {
              value: item?.id,
              label: item?.areaName,
            };
          });
          setPartitions(arr || []);

          let reslut2 = await fetchDictInfo(DATABASE_TYPE_ENUM.DEVICE_TYPE);
          setDeviceList(reslut2 || []);
        }
      } catch (error) {}
    })();
  }, []);

  const findNode = (name: string) => {
    let nodeReturn = null;
    if (params.treeData.length) {
      for (let node of params.treeData[0]?.children) {
        if (node?.title === name) {
          nodeReturn = node;
          break;
        }
      }
    }
    return nodeReturn;
  };

  const fetchDeviceType = async () => {
    const result = await realTimeMonitoringControllerDeviceTypes({
      deviceCode: deviceNode?.deviceCode ?? undefined,
      areId: deviceNode?.areaId ?? undefined,
      deviceType: deviceNode?.deviceType ?? '',
    });
    return (result.data || []).map((item) => {
      return {
        label: item.name,
        value: item.type,
      };
    });
  };

  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.zoneName' }),
      dataIndex: 'areaId',
      valueType: 'select',
      fieldProps: {
        options: partitions,
        // mode: 'multiple',
        maxTagCount: 'responsive',
      },
      hideInSearch: !showArea,
      hideInTable: !showArea,
      render: (_, record) => (
        <a
          onClick={() => {
            let node = findNode(record?.areaName);
            setSelectedDevice1(node);
          }}
        >
          {record.areaName}
        </a>
      ),
    },
    {
      title: intl.formatMessage({ id: 'siteManage.deviceType' }),
      dataIndex: 'deviceType',
      valueType: 'select',
      fieldProps: {
        maxTagCount: 'responsive',
        // options: deviceList,
      },
      request: fetchDeviceType,
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.offlineDevice' }),
      dataIndex: 'deviceName',
      valueType: 'text',
      render: (_, record) => {
        return record?.offlineDevice;
      },
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.collectTime' }),
      dataIndex: 'lastReportTime',
      valueType: 'dateTimeRange',
      search: {
        transform: (value: any) => {
          return {
            offlineStartDatetime: value ? value[0] : null,
            offlineEndDatetime: value ? value[1] : null,
          };
        },
      },
      render: (_, record) => {
        return record?.lastReportTime;
      },
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.offlineDuration' }),
      dataIndex: 'offlineDuration',
      valueType: 'select',
      fieldProps: {
        // mode: 'multiple',
        maxTagCount: 'responsive',
        options: [
          { label: intl.formatMessage({ id: 'stationRealtimeMonitoring.off1' }), value: 'LT-3600' },
          { label: intl.formatMessage({ id: 'stationRealtimeMonitoring.off2' }), value: 'LT-7200' },
          {
            label: intl.formatMessage({ id: 'stationRealtimeMonitoring.off6' }),
            value: 'LT-21600',
          },
          {
            label: intl.formatMessage({ id: 'stationRealtimeMonitoring.off12' }),
            value: 'LT-43200',
          },
          {
            label: intl.formatMessage({ id: 'stationRealtimeMonitoring.offD1' }),
            value: 'LT-86400',
          },
          {
            label: intl.formatMessage({ id: 'stationRealtimeMonitoring.offD7' }),
            value: 'LT-604800',
          },
          {
            label: intl.formatMessage({ id: 'stationRealtimeMonitoring.offDThan7' }),
            value: 'GE-604800',
          },
        ],
      },
      search: {
        transform: (value) => {
          let paramsValue = value?.split('-');
          if (paramsValue && paramsValue.length === 2) {
            return {
              offlineDurationCondition: paramsValue[0],
              offlineDuration: paramsValue[1],
            };
          } else {
            return {};
          }
        },
      },
    },
  ];

  const scroll = {
    x: 'max-content',
    y: 460,
  };

  return (
    <div>
      <ProTable
        columns={columns}
        className={Styles.hideXscroll}
        headerTitle=""
        params={{
          deviceCode: deviceNode?.deviceCode ?? undefined,
        }}
        request={async (values) => {
          try {
            let params = {
              deviceType: deviceNode?.deviceType ?? undefined,
              ...values,
            };
            let reslut = await offList(params);
            return reslut;
          } catch (err) {
            console.log(err, '错误');
          }
        }}
        rowKey="pageIndex"
        scroll={scroll}
        sticky
        search={{
          defaultCollapsed: false,
        }}
        pagination={{
          showQuickJumper: true,
        }}
        dateFormatter="string"
      />
    </div>
  );
};
